const express = require("express");
const router = express.Router();
const multipart = require("connect-multiparty");
const multer = require("multer");
const path = require("path");
const fs = require("fs");

const multipartMiddleware = multipart();
// const upload = multer({
//   dest: path.resolve(__dirname, "../fileUpload"),
// });

router.post(
  "/uploadFile",
  multipartMiddleware,
  (req, res, next) => {
    const files = req.files; //这个就是前端传来的文件
    const { fileName, currentChunk, totalChunks } = req.body;
    const file = files.file;
    const filePath = path.resolve(__dirname, "../fileUpload/" + fileName);
    console.log(filePath);

    // 创建写入流
    // const writeStream = fs.fileWriteStream(filePath);
    // fs.createReadStream(file.path).pipe(writeStream);
    var source = fs.createReadStream(file.path);
    var dest = fs.createWriteStream(filePath);

    source.pipe(dest);
    source.on("end", function () {
      fs.unlinkSync(file.path);
    }); //delete
    source.on("error", function (err) {});

    next();
  },
  (req, res) => {
    res.status(200).send({
      code: 1,
      data: {},
      message: "响应成功~~~",
    });
  }
);

module.exports = router;
